# 'Friendly Flow' is a Server Framework for Python 2.5 and up
# Copyright (C) Xaba Software http://www.xaba.nl/
#
# This file is part of 'Friendly Flow'
#
# 'Friendly Flow' is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# 'Friendly Flow' is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with 'Friendly Flow'; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

from unittest import TestCase
from traceback import format_exc

from friendlyflow import RETURN, flatten

class TestException(Exception):
    pass

class FlattenTest(TestCase):
    
    def testValues(self):
        def f():
            yield "a"
            yield "b"
        
        output = list(flatten(f()))
        self.assertEquals(["a", "b"], output)
        
    def testNoneValuesAreValidValues(self):
        def f():
            yield None
            yield None
            
        def g():
            yield f()
        
        output = list(flatten(f()))
        self.assertEquals([None, None], output)
        
        output = list(flatten(g()))
        self.assertEquals([None, None], output)
            
    def testSimpleCall(self):
        l = []
        def f():
            if False:
                yield
            l.append("f called")

        def g():
            l.append("g called")
            yield f()

        output = list(flatten(g()))
        self.assertEquals([], output)
        self.assertEquals(["g called", "f called"], l)
        
    def testTwoLevelCall(self):
        l = []
        def f():
            if False:
                yield
            l.append("f called")

        def g():
            l.append("g called")
            yield f()
            
        def h():
            l.append("h called")
            yield g()

        output = list(flatten(h()))
        self.assertEquals([], output)
        
        self.assertEquals(["h called", "g called", "f called"], l)

    def testReturnInOutmostGenerator(self):
        #this is required to be able to call flatten at any codepoint
        def f():
            yield RETURN("f return value")

        output = list(flatten(f()))
        self.assertEquals([RETURN("f return value")], output)

    def testReturnIsReturned(self):
        l = []
        def f():
            yield RETURN("f return value")

        def g():
            returnValue = yield f()
            l.append(returnValue)

        output = list(flatten(g()))
        self.assertEquals([], output)
        self.assertEquals(["f return value"], l)

    def testReturnEndsMethod(self):
        l = []
        def f():
            yield RETURN("f return value")
            yield RETURN("f return value 2 - makes no sense")

        def g():
            returnValue = yield f()
            l.append(returnValue)

        output = list(flatten(g()))
        self.assertEquals([], output)
        self.assertEquals(["f return value"], l)

    def testTwoLevelReturn(self):
        l = []
        def f():
            yield RETURN("f return value")

        def g():
            returnValue = yield f()
            yield RETURN(returnValue)
            
        def h():
            returnValue = yield g()
            l.append(returnValue)

        output = list(flatten(h()))
        self.assertEquals([], output)
        self.assertEquals(["f return value"], l)

    def testNoReturnIsImplicitlyNone(self):
        l = []
        def f():
            yield "no return"

        def g():
            returnValue = yield f()
            l.append(returnValue)

        output = list(flatten(g()))
        self.assertEquals(["no return"], output)
        self.assertEquals([None], l)

    def testExceptionIsCaught(self):
        l = []
        def f():
            if False:
                yield
            raise TestException('exception in f')
            
        def g():
            try:
                yield f()
            except TestException, e:
                l.append(str(e))
        
        output = list(flatten(g()))
        self.assertEquals([], output)
        self.assertEquals(["exception in f"], l)

    def testExceptionIsCaughtDeeply(self):
        l = []
        def f():
            if False:
                yield
            raise TestException('exception in f')
            
        def g():
            yield f()
        
        def h():
            try:
                yield g()
            except TestException, e:
                l.append(str(e))
        
        output = list(flatten(h()))
        self.assertEquals([], output)
        self.assertEquals(["exception in f"], l)

    def testExceptionRecoversAndReturns(self):
        l = []
        def f():
            if False:
                yield
            raise TestException('exception in f')
            
        def g():
            try:
                yield f()
            except TestException, e:
                yield RETURN(str(e))
        
        def h():
            returnValue = yield g()
            l.append(returnValue)
        
        output = list(flatten(h()))
        self.assertEquals([], output)
        self.assertEquals(["exception in f"], l)

    def testUncaughtException(self):
        def f():
            if False:
                yield
            raise TestException('exception in f')
            
        def g():
            yield f()
        
        try:
            list(flatten(g()))
            self.fail()
        except TestException, e:
            pass

    def testExceptionTriggersFinally(self):
        l = []
        def f():
            if False:
                yield
            raise TestException('exception in f')
            
        def g():
            try:
                yield f()
            finally:
                l.append("finally in g")
        
        try:
            list(flatten(g()))
            self.fail()
        except TestException, e:
            pass

        self.assertEquals(["finally in g"], l)
        
    def testCaughtExceptionRaisesException(self):
        l = []
        def f():
            if False:
                yield
            raise TestException('exception in f')
            
        def g():
            try:
                yield f()
            except TestException, e:
                raise TestException('exception in g')
        
        def h():
            try:
                returnValue = yield g()
                l.append(returnValue)
            except Exception, e:
                l.append(str(e))
        
        list(flatten(h()))
        self.assertEquals(["exception in g"], l)
    
    def testStackTrace(self):
        def f():
            if False:
                yield
            raise TestException('exception in f')
            
        def g():
            yield f()
        
        def h():
            yield g()
        
        try:
            list(flatten(h()))
        except:
            traceback = format_exc()
        
        self.assertTrue(", in h" in traceback)
        self.assertTrue("yield g()" in traceback, traceback)
        self.assertTrue(", in g" in traceback)
        self.assertTrue("yield f()" in traceback)
        self.assertTrue(", in f" in traceback)
        self.assertTrue("raise TestException('exception in f')" in traceback)

